import { useState } from "react";
import { useRequest } from "ahooks";
import type { TableColumnsType, TableProps } from "antd";
import { Button, Flex, Switch, Tooltip } from "antd";
import SearchForm from "@/components/search-form";
import Table from "@/components/table";
import VideoPreview from "@/components/video-preview";
// import CreateButton from "./components/create-button";
import EditButton from "./components/edit-button";
import StatusModal from "./components/status-modal";
import { updateMaterialStatus, useUserList } from "./api";
import { MaterialDataType } from "./types";

interface DataType {
  key: string;
  id: number;
  name: string;
  phone: string;
  email: string;
  company: any;
  status?: "enabled" | "disabled";
}

type TableRowSelection<T extends object = object> = TableProps<T>["rowSelection"];

export default function MaterialManagement() {
  const { data, isFetching, refetch } = useUserList();
  const [queryParams, setQueryParams] = useState({
    pageNum: 1,
    pageSize: 10,
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRecords, setSelectedRecords] = useState<DataType[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: data?.length,
  });

  // Modal状态
  const [openStatusModal, setOpenStatusModal] = useState(false);
  const [currentActionData, setCurrentActionData] = useState<DataType | DataType[] | null>(null);
  const [batchLoading, setBatchLoading] = useState(false);

  // 统一的状态更新API
  const { run: runUpdateStatus, loading: isUpdating } = useRequest(
    async (data: { id: number; status: "enabled" | "disabled" }) => updateMaterialStatus(data),
    { manual: true },
  );

  // 检查选中项的状态一致性
  const checkStatusConsistency = (records: DataType[]) => {
    if (records.length === 0) return { isConsistent: false, status: null };
    const firstStatus = records[0].status || "disabled";
    const isConsistent = records.every((record) => (record.status || "disabled") === firstStatus);
    return { isConsistent, status: firstStatus };
  };

  // 批量开启处理
  const handleBatchEnable = () => {
    if (selectedRecords.length === 0) {
      window.$message?.warning("请选择要操作的素材");
      return;
    }

    const { isConsistent, status } = checkStatusConsistency(selectedRecords);

    if (!isConsistent) {
      window.$message?.warning("选择的素材包含多个状态，需一致哦");
      return;
    }

    if (status === "enabled") {
      window.$message?.info("素材状态已启用");
      return;
    }

    // 状态为 disabled，需要二次确认
    setCurrentActionData(selectedRecords);
    setOpenStatusModal(true);
  };

  // 批量关闭处理
  const handleBatchDisable = () => {
    if (selectedRecords.length === 0) {
      window.$message?.warning("请选择要操作的素材");
      return;
    }

    const { isConsistent, status } = checkStatusConsistency(selectedRecords);

    if (!isConsistent) {
      window.$message?.warning("选择的素材包含多个状态，需一致哦");
      return;
    }

    if (status === "disabled") {
      window.$message?.info("素材状态已关闭");
      return;
    }

    // 状态为 enabled，需要二次确认
    setCurrentActionData(selectedRecords);
    setOpenStatusModal(true);
  };

  // 单个状态切换处理
  const handleSingleToggle = (record: DataType) => {
    const currentStatus = record.status || "disabled";

    if (currentStatus === "enabled") {
      // 已开启 -> 需要二次确认关闭
      setCurrentActionData(record);
      setOpenStatusModal(true);
    } else {
      // 已停用 -> 需要二次确认开启
      setCurrentActionData(record);
      setOpenStatusModal(true);
    }
  };

  // 执行单个状态更新
  const handleSingleUpdate = async (record: DataType, targetStatus: "enabled" | "disabled") => {
    try {
      // TODO: 调用API更新状态
      await runUpdateStatus({
        id: record.id,
        status: targetStatus,
      });
      window.$message?.success(targetStatus === "enabled" ? "开启成功" : "关闭成功");
      refetch();
    } catch {
      window.$message?.error("操作失败");
    }
  };

  // 执行批量状态更新
  const handleBatchUpdate = async (records: DataType[], targetStatus: "enabled" | "disabled") => {
    setBatchLoading(true);
    try {
      // TODO: 调用API批量更新状态
      const results = await Promise.allSettled(
        records.map((record) =>
          updateMaterialStatus({
            id: record.id,
            status: targetStatus,
          }),
        ),
      );

      const successCount = results.filter((result) => result.status === "fulfilled").length;
      const failCount = results.length - successCount;

      if (failCount === 0) {
        window.$message?.success(targetStatus === "enabled" ? "批量开启成功" : "批量关闭成功");
        setSelectedRowKeys([]);
        setSelectedRecords([]);
      } else {
        window.$message?.error(`操作完成，成功${successCount}条，失败${failCount}条`);
      }

      refetch();
    } catch {
      window.$message?.error("批量操作失败");
    } finally {
      setBatchLoading(false);
    }
  };

  // Modal确认处理
  const handleStatusConfirm = () => {
    if (!currentActionData) return;

    if (Array.isArray(currentActionData)) {
      // 批量处理
      const targetStatus = currentActionData[0].status === "disabled" ? "enabled" : "disabled";
      handleBatchUpdate(currentActionData, targetStatus);
    } else {
      // 单个处理
      const targetStatus = currentActionData.status === "disabled" ? "enabled" : "disabled";
      handleSingleUpdate(currentActionData, targetStatus);
    }

    setOpenStatusModal(false);
    setCurrentActionData(null);
  };

  const columns: TableColumnsType<DataType> = [
    {
      title: "视频预览",
      dataIndex: "videoPreview",
      key: "videoPreview",
      width: 300,
      render: (_, record) =>
        record.id === 1 && (
          <VideoPreview
            key={record.id}
            src={"https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4"}
            poster="https://picsum.photos/200/300"
            width={280}
            height={158}
          />
        ),
    },
    {
      title: "视频路径",
      dataIndex: "videoPath",
      key: "videoPath",
    },
    {
      title: "视频状态",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "所属类目",
      dataIndex: "website",
      key: "website",
    },
    {
      title: "二级类目",
      dataIndex: "company",
      key: "company",
      render: (_, record) => record.company.name,
    },
    {
      title: "创建时间",
      dataIndex: "waitingReview",
      key: "waitingReview",
      render: (_, record) => record.company.name,
    },
    {
      title: "分析用时",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (_, record) => record.company.name,
    },
    {
      title: "用户端",
      dataIndex: "lastLoginAt",
      key: "lastLoginAt",
      render: (_, record) => record.company.name,
    },
    {
      title: "收藏",
      dataIndex: "lastLoginIp",
      key: "lastLoginIp",
      render: (_, record) => record.company.name,
    },
    {
      title: "复刻",
      dataIndex: "status",
      key: "status",
      render: (_, record) => record.company.name,
    },
    {
      title: "下载分享",
      dataIndex: "status",
      key: "status",
      render: (_, record) => record.company.name,
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      fixed: "right",
      width: 100,
      render: (_, record) => {
        return (
          <Flex gap={8}>
            <EditButton data={record} />
            <Tooltip title={(record.status || "disabled") === "enabled" ? "状态关闭" : "状态开启"}>
              <Flex align="center">
                <Switch
                  size="small"
                  checked={(record.status || "disabled") === "enabled"}
                  loading={isUpdating && !batchLoading}
                  onChange={() => handleSingleToggle(record)}
                />
              </Flex>
            </Tooltip>
          </Flex>
        );
      },
    },
  ];

  const canHideColumns: TableColumnsType<DataType> = [
    {
      title: "用户ID",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "用户昵称",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "手机号",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "小红书账号",
      dataIndex: "website",
      key: "website",
    },
  ];

  const schema = [
    {
      name: "createdAt",
      label: "创建时间",
      type: "datepicker",
      componentProps: { name: "createdAt", placeholder: "年/月/日" },
    },
    {
      name: "cardCount",
      label: "所属类目",
      type: "select",
      componentProps: {
        options: [
          { label: "正常", value: 1 },
          { label: "禁用", value: 0 },
        ],
      },
    },
    {
      name: "status",
      label: "分析状态",
      type: "select",
      componentProps: {
        options: [
          { label: "正常", value: 1 },
          { label: "禁用", value: 0 },
        ],
      },
    },
  ];

  const onSearch = (values: any) => {
    const newParams = {
      ...values,
      pageNum: 1, // 搜索时重置为第一页
      pageSize: pagination.pageSize,
    };
    setQueryParams(newParams);
    setPagination({ ...pagination, current: 1 });
    // fetchList(newParams);
  };

  const onPageChange = (page: number, pageSize: number) => {
    const newParams = {
      ...queryParams,
      pageNum: page,
      pageSize: pageSize,
    };
    setQueryParams(newParams);
    setPagination({
      ...pagination,
      current: page,
      pageSize: pageSize,
    });

    // 手动触发查询
    // fetchList(newParams);
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    // 获取选中的完整记录
    const selectedRecords = data?.filter((item: DataType) => newSelectedRowKeys.includes(item.id)) || [];
    setSelectedRecords(selectedRecords);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  return (
    <div className="flex flex-col h-full overflow-hidden">
      <div className="mb-4 bg-white rounded-lg p-4 dark:bg-[#1f1f1f] flex-shrink-0">
        <SearchForm schema={schema} onSearch={onSearch} />
      </div>
      <div className="bg-white rounded-lg p-4 dark:bg-[#1f1f1f] flex-1 flex flex-col overflow-hidden">
        <Table
          rowKey="id"
          columns={columns}
          canHideColumns={canHideColumns}
          dataSource={data}
          loading={isFetching}
          pagination={pagination}
          rowSelection={rowSelection}
          onPageChange={onPageChange}
          onRefresh={refetch}
          leftActions={
            <>
              {/* <CreateButton /> */}
              <Button
                size="middle"
                type="primary"
                disabled={selectedRowKeys.length === 0}
                loading={batchLoading}
                onClick={handleBatchEnable}
              >
                开启
              </Button>
              <Button
                size="middle"
                type="primary"
                ghost
                disabled={selectedRowKeys.length === 0}
                loading={batchLoading}
                onClick={handleBatchDisable}
              >
                关闭
              </Button>
            </>
          }
        />
      </div>

      <StatusModal
        open={openStatusModal}
        data={currentActionData as MaterialDataType | MaterialDataType[] | null}
        onClose={() => {
          setOpenStatusModal(false);
          setCurrentActionData(null);
        }}
        onConfirm={handleStatusConfirm}
        loading={Array.isArray(currentActionData) ? batchLoading : isUpdating}
      />
    </div>
  );
}
